<template>
  <div class="app-container">
    <div class="servicePackageListDivDialog">
      <div class="servicePackageListDivSpan">服务部署</div>
    </div>
    <div class="servicePackageListChild">
      <div class="deployInfoDiv">
        <!-- 服务信息输入框 -->
        <div>
          <div class="displayLayout">
            <el-row>
              <el-col :span="8">
                <div>
                  <span class="spanStyle"> 服务标识： </span>
                  <el-input placeholder="请输入服务标识" style="width: 250px"
                    v-model="gvStoreYamlDeployVo.yamlDeployBaseInfo.appName" disabled>
                  </el-input>
                </div>
              </el-col>
              <el-col :span="8">
                <div>
                  <span class="spanStyle"> 服务版本： </span>
                  <el-input placeholder="请输入服务版本" style="width: 250px"
                    v-model="gvStoreYamlDeployVo.yamlDeployBaseInfo.version" disabled>
                  </el-input>
                </div>
              </el-col>
              <!-- 分区信息 -->
              <el-col :span="8">
                <div>
                  <span class="spanStyle"> 分区选择： </span>
                  <el-select v-model="gvStoreYamlDeployVo.partitionZhname" placeholder="请选择服务版本" style="width: 250px"
                    @change="handlePartitionChange">
                    <el-option v-for="item in partitionOptions" :key="item.id" :label="item.partitionZhname"
                      :value="item.partitionZhname" :data-id="item.id"></el-option>
                  </el-select>
                  <el-tooltip class="item" effect="dark" content="服务部署至指定集群分区节点，非必选项" placement="bottom-start"><i
                      class="el-icon-question"
                      style="font-size: 25px; color: slategray; margin-left: 8px"></i></el-tooltip>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="displayLayout">
            <el-row>
              <el-col :span="8">
                <div>
                  <span class="spanStyle"> 服务镜像： </span>
                  <el-input placeholder="请输入服务镜像" style="width: 250px"
                    v-model="gvStoreYamlDeployVo.yamlDeployBaseInfo.image" disabled>
                  </el-input>
                </div>
              </el-col>
              <el-col :span="8">
                <div>
                  <span class="spanStyle"> 服务描述： </span>
                  <el-input placeholder="请输入服务描述" clearable style="width: 250px"
                    v-model="gvStoreYamlDeployVo.yamlDeployBaseInfo.description">
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="displayLayout">
            <el-row>
              <el-col :span="8">
                <div>
                  <span class="spanStyle"> 部署名称： </span>
                  <el-input placeholder="请输入部署名称" clearable style="width: 250px"
                    v-model="gvStoreYamlDeployVo.yamlDeployBaseInfo.deployName" @blur="checkDeployName">
                  </el-input>
                </div>
              </el-col>
              <el-col :span="8">
                <div>
                  <span class="spanStyle"> 副本数量： </span>
                  <el-input-number placeholder="请输入服本数量" type="number" style="width: 250px"
                    v-model="gvStoreYamlDeployVo.yamlDeployBaseInfo.replicas" :min="1" :max="100" :step="1">
                  </el-input-number>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div style="float: right; margin-top: 10px">
          <el-switch v-model="expandSwitch" active-color="#13ce66" inactive-color="#eeeeee" active-text="展开"
            @change="expandAll">
          </el-switch>
        </div>
        <div style="margin-top: 40px">
          <div>
            <el-collapse v-model="activeName" :accordion="accordionType">
              <el-collapse-item title="端口设置" name="1">
                <div v-for="(
portInfo, index
                  ) in gvStoreYamlDeployVo.yamlDeployPortInfo" :key="portInfo.port" style="margin-bottom: 5px">
                  <el-row>
                    <el-col :span="4">
                      <span class="spanStyle"> 协议： </span>
                      <el-input :disabled="true" style="width: 120px" v-model="portInfo.protocol">
                      </el-input>
                    </el-col>
                    <el-col :span="4">
                      <span class="spanStyle"> 内部端口： </span>
                      <el-input style="width: 120px" v-model="portInfo.port" disabled>
                      </el-input>
                    </el-col>
                    <el-col :span="6">
                      <span class="spanStyle"> 暴露端口： </span>
                      <el-input style="width: 120px" v-show="!portInfo.fixed" disabled placeholder="随机端口">
                      </el-input>
                      <el-input style="width: 120px" v-model="portInfo.port" v-show="portInfo.fixed" disabled>
                      </el-input>
                      <el-checkbox v-model="portInfo.fixed" style="margin-left: 10px"
                        @change="changePortWithContainer(index)">
                        <span class="spanStyle"> 容器一致 </span>
                      </el-checkbox>
                    </el-col>
                    <el-col :span="4">
                      <el-switch active-text="开启域名" v-model="portInfo.enableDns">
                      </el-switch>
                    </el-col>
                    <el-col :span="4" v-show="portInfo.enableDns">
                      <span class="spanStyle"> DNS： </span>
                      <el-input style="width: 120px" v-model="portInfo.dns" @blur="checkDnsValue(portInfo.dns)">
                      </el-input>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
              <el-collapse-item title="资源配置" name="2">
                <div>
                  <el-row>
                    <el-col :span="8">
                      <div style="margin-bottom: 5px">
                        <span class="spanStyle"> CPU预留： </span>
                        <el-input style="width: 250px" v-model="gvStoreYamlDeployVo.yamlDeployResourceInfo
                          .cpuRequest
                          " controls-position="right" :min="0.1" :max="256" :step="0.1" type="number" @blur="checkCpu">
                          <template v-slot:append>核</template>
                        </el-input>
                      </div>
                      <div v-show="gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit
                        ">
                        <span class="spanStyle"> CPU限制： </span>
                        <el-input style="width: 250px" v-model="gvStoreYamlDeployVo.yamlDeployResourceInfo.cpuLimit
                          " controls-position="right" :min="0.1" :max="256" :step="0.1" type="number" @blur="checkCpu">
                          <template v-slot:append>核</template>
                        </el-input>
                      </div>
                      <div>
                        <span class="spanStyle"> CPU可用： </span>
                        <span>{{ remainResourceInfo.cpu }}核</span>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div style="margin-bottom: 5px">
                        <span class="spanStyle"> 内存预留： </span>
                        <el-input style="width: 250px" v-model="gvStoreYamlDeployVo.yamlDeployResourceInfo
                          .memRequest
                          " controls-position="right" :min="4" :max="16384" :step="256" type="number"
                          @blur="checkMemory">
                          <template v-slot:append>MB</template>
                        </el-input>
                      </div>
                      <div v-show="gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit
                        ">
                        <span class="spanStyle"> 内存限制： </span>
                        <el-input style="width: 250px" v-model="gvStoreYamlDeployVo.yamlDeployResourceInfo.memLimit
                          " controls-position="right" :min="4" :max="16384" :step="256" type="number"
                          @blur="checkMemory">
                          <template v-slot:append>MB</template>
                        </el-input>
                      </div>
                      <div>
                        <span class="spanStyle"> 内存可用： </span>
                        <span>{{ remainResourceInfo.memory }}MB</span>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <el-switch v-model="gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit
                        " active-color="#13ce66" inactive-color="#ff4949" :active-text="resourceLimitText"
                        @change="changeResourceLimitStatus">
                      </el-switch>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
              <el-collapse-item name="3" title="自动伸缩">
                <!--                <template slot="title">-->
                <!--                  自动伸缩-->
                <!--                  <el-switch-->
                <!--                    v-model="gvStoreYamlDeployVo.enableHpa"-->
                <!--                    active-color="#13ce66"-->
                <!--                    inactive-color="#989898"-->
                <!--                    style="margin-left: 20px"-->
                <!--                  >-->
                <!--                  </el-switch>-->
                <!--                </template>-->
                <div>
                  <el-switch v-model="gvStoreYamlDeployVo.enableHpa" active-color="#13ce66" inactive-color="#989898"
                    :active-text="openHpaText" @change="changeHpaStatus">
                  </el-switch>
                </div>
                <div v-if="gvStoreYamlDeployVo.enableHpa" style="margin-top: 4px">
                  <el-row style="margin-bottom: 5px">
                    <el-col :span="8">
                      <span class="spanStyle"> 触发条件： </span>
                      <el-select v-model="metricsInfo.type" placeholder="请选择" style="width: 100px; margin-right: 10px">
                        <el-option v-for="selectMetrics in selectMetricsList" :key="selectMetrics.value"
                          :label="selectMetrics.label" :value="selectMetrics.value">
                        </el-option>
                      </el-select>
                      <span class="spanStyle"> 使用量： </span>
                      <el-input-number style="width: 100px" v-model="metricsInfo.usage" controls-position="right"
                        :min="1" :max="99" :step="1">
                      </el-input-number>
                      %
                      <el-button type="primary" size="mini" icon="el-icon-plus" circle style="margin-left: 10px"
                        @click="addHapInfoMetrics" class="el-button-primary-style"></el-button>
                    </el-col>
                    <el-col :span="4" v-for="(mt, index) in gvStoreYamlDeployVo
                      .yamlDeployHpaInfo.metrics" :key="mt.type">
                      <span class="spanStyle">
                        类型：{{ mt.type }} - 值：{{ mt.usage }} %
                        <el-button type="primary" size="mini" icon="el-icon-delete" circle style="margin-left: 10px"
                          @click="deleteMetrics(index)" class="el-button-primary-style"></el-button>
                      </span>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="15">
                      <span class="spanStyle"> 伸缩范围： </span>
                      <el-input-number style="width: 100px" v-model="gvStoreYamlDeployVo.yamlDeployHpaInfo.minReplicas
                        " controls-position="right" :min="1" :max="99" :step="1" @blur="checkReplicas">
                      </el-input-number>
                      ～
                      <el-input-number style="width: 100px" v-model="gvStoreYamlDeployVo.yamlDeployHpaInfo.maxReplicas
                        " controls-position="right" :min="1" :max="99" :step="1" @blur="checkReplicas">
                      </el-input-number>
                      <span style="margin-left: 10px">注：1-99之间</span>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
              <el-collapse-item title="配置挂载" name="4" v-if="gvStoreYamlDeployVo.yamlDeployConfigInfo.length !== 0">
                <div v-for="(
deployConfigInfo, index
                  ) in gvStoreYamlDeployVo.yamlDeployConfigInfo" :key="index" style="margin-bottom: 5px">
                  <el-row>
                    <el-col :span="5">
                      <span class="spanStyle"> 文件名称： </span>
                      <el-input style="width: 150px" v-model="deployConfigInfo.mountFilename" disabled>
                      </el-input>
                    </el-col>
                    <el-col :span="8">
                      <span class="spanStyle"> 挂载路径： </span>
                      <el-input style="width: 350px" v-model="deployConfigInfo.mountPath" disabled>
                      </el-input>
                    </el-col>
                    <el-col :span="3">
                      <el-button type="primary" size="small" @click="
                        getFileDataById(
                          gvStoreYamlDeployVo.yamlDeployBaseInfo.appId,
                          deployConfigInfo.mountPath,
                          deployConfigInfo.mountFiledata
                        )
                        " class="el-button-primary-style">
                        编 辑
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
              <el-collapse-item title="存储挂载" name="5" v-if="gvStoreYamlDeployVo.yamlDeployVolumeInfo.length !== 0">
                <div v-for="(
deployVolumeInfo, index
                  ) in gvStoreYamlDeployVo.yamlDeployVolumeInfo" :key="index" style="margin-bottom: 5px">
                  <el-row>
                    <el-col :span="3">
                      <el-switch v-model="deployVolumeInfo.autoCreate" active-color="#13ce66" inactive-color="#989898"
                        :active-text="deployVolumeInfo.autoCreate ? '自动创建' : '选择已有'
                          ">
                      </el-switch>
                    </el-col>
                    <el-col :span="8">
                      <span class="spanStyle"> 挂载路径： </span>
                      <el-input style="width: 300px" v-model="deployVolumeInfo.mountPath">
                      </el-input>
                    </el-col>
                    <el-col :span="6" v-show="deployVolumeInfo.autoCreate">
                      <span class="spanStyle"> 挂载模式： </span>
                      <el-select v-model="deployVolumeInfo.accessMode" placeholder="请选择挂载模式">
                        <el-option v-for="item in volumeAccessMode" :key="item" :label="item" :value="item">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="6" v-show="!deployVolumeInfo.autoCreate">
                      <span class="spanStyle"> 已有挂载： </span>
                      <el-select v-model="deployVolumeInfo.pvcId" placeholder="请选择已存在的挂载卷">
                        <el-option v-for="item in existPvcList" :key="item.id" :label="item.pvcName" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="5" v-show="deployVolumeInfo.autoCreate">
                      <span class="spanStyle"> 挂载容量： </span>
                      <el-input style="width: 180px" v-model="deployVolumeInfo.capacity" controls-position="right"
                        :min="0" :max="1024" :step="1" type="number">
                        <template v-slot:append>GB</template>
                      </el-input>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
              <el-collapse-item title="环境变量" name="6">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <div style="margin-bottom: 5px">KEY</div>
                  </el-col>
                  <el-col :span="6">
                    <div style="margin-bottom: 5px">VALUE</div>
                  </el-col>
                  <el-col :span="11">
                    <div style="float: right">
                      <el-button type="primary" round size="small" @click="addNewEnv" class="el-button-primary-style">
                        <i class="el-icon-plus"></i>新增
                      </el-button>
                    </div>
                  </el-col>
                </el-row>
                <div v-for="(
envInfo, index
                  ) in gvStoreYamlDeployVo.yamlDeployEnvInfo" :key="index">
                  <el-row :gutter="20">
                    <el-col :span="6">
                      <div style="margin-bottom: 5px">
                        <el-input v-model="envInfo.key" :disabled="index < gvEnvLength" @blur="judgeReg(index)">
                        </el-input>
                      </div>
                    </el-col>
                    <el-col :span="6">
                      <div style="margin-bottom: 5px">
                        <el-input v-model="envInfo.value" @blur="judgeReg(index)"></el-input>
                      </div>
                    </el-col>
                    <el-col :span="3">
                      <el-button type="primary" class="el-button-primary-style" size="small"
                        @click="deleteEnvForEnvList(index)" v-show="index >= gvEnvLength">删除
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
        <div class="deployButtonDiv">
          <el-button type="primary" size="small" @click="deployThePackage" class="el-button-primary-style">部 署
          </el-button>
          <el-button type="primary" size="small" @click="cancelDeploy" class="el-button-primary-style">取 消
          </el-button>
        </div>
      </div>
    </div>
    <div>
      <el-dialog title="查看并编辑配置文件" :visible.sync="editConfigFileDialog" width="60%" :close-on-press-escape="false"
        :close-on-click-modal="false" :destroy-on-close="true">
        <div>
          <el-input type="textarea" v-model="configFileContext" :rows="24"></el-input>
        </div>
        <div class="deployButtonDiv">
          <el-button type="primary" size="small" @click="saveConfigFileContext" class="el-button-primary-style">保 存
          </el-button>
          <el-button type="primary" size="small" @click="closeEditConfigFileDialog" class="el-button-primary-style">取 消
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getTenantId } from "@/utils/tenantId";

export default {
  name: "ServiceDeploy",
  data() {
    return {
      activeName: "0",
      accordionType: true,
      expandSwitch: false,
      openHpaText: "关闭自动伸缩",
      gvStoreYamlDeployVo: {
        tenantId: "",
        yamlDeployBaseInfo: {
          appName: "",
          deployName: "",
          version: "",
          image: "",
          description: "",
          replicas: 1,
        },
        yamlDeployPortInfo: [],
        yamlDeployResourceInfo: {
          cpuRequest: 0,
          memRequest: 0,
          cpuLimit: 0,
          memLimit: 0,
        },
        enableHpa: false,
        yamlDeployHpaInfo: {
          maxReplicas: 10,
          minReplicas: 0,
          metrics: [],
        },
        yamlDeployConfigInfo: [],
        yamlDeployVolumeInfo: [],
        yamlDeployEnvInfo: [],
        livenessInfoOffline: {
          // 冒烟测试类型 url,file,program
          type: "",
          port: 0,
          portType: "",
          url: "",
          command: [],
          initialDelaySeconds: 0,
          periodSeconds: 0,
          timeoutSeconds: 0,
          persistentConnection: false,
          successThreshold: 0,
          failureThreshold: 0,
        },
        readinessInfoOffline: {
          // 冒烟测试类型 url,file,program
          type: "",
          port: 0,
          portType: "",
          url: "",
          command: [],
          initialDelaySeconds: 0,
          periodSeconds: 0,
          timeoutSeconds: 0,
          persistentConnection: false,
          successThreshold: 0,
          failureThreshold: 0,
        },
        yamlDeployLoadInfo: {
          isImageLoader: false,
          baseImageName: "",
          baseImageVersion: "",
          startCmdList: [],
          loadingModeKeyValues: []
        },
        partitionZhname: "",
        partitionId: "",
      },
      partitionOptions: [], // 存储分区数据
      metricsInfo: {
        type: "",
        usage: 0,
      },
      selectMetricsList: [
        {
          value: "cpu",
          label: "CPU",
        },
        {
          value: "memory",
          label: "内存",
        },
      ],
      gvEnvLength: 0,
      resourceLimitText: "开启资源限制",
      volumeAccessMode: ["ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany"],
      existPvcList: [],
      editConfigFileDialog: false,
      configFileContext: "",
      mountPath: "",
      remainResourceInfo: {
        cpu: 0,
        memory: 0,
      },
    };
  },
  created() {
    this.fetchPartitionOptions();
  },
  methods: {
    // 获取分区信息
    async fetchPartitionOptions() {
      await this.$appManageApi.getPartitionOptions().then((res) => {
        if (res && res.code === 200) {
          // 确保 id 是字符串格式
          this.partitionOptions = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 处理分区选择
    handlePartitionChange(selectedZhname) {
      const selectedPartition = this.partitionOptions.find(
        (item) => item.partitionZhname === selectedZhname
      );

      if (selectedPartition) {
        this.gvStoreYamlDeployVo.partitionId = selectedPartition.id;
        this.gvStoreYamlDeployVo.partitionZhname = selectedPartition.partitionZhname;
      }
    },
    changeHpaStatus(status) {
      if (status) {
        this.openHpaText = "开启自动伸缩";
      } else {
        this.openHpaText = "关闭自动伸缩";
      }
    },
    expandAll() {
      if (this.expandSwitch) {
        this.accordionType = false;
        this.activeName = ["1", "2", "3", "4", "5", "6"];
      } else {
        this.accordionType = true;
        this.activeName = "0";
      }
    },
    checkReplicas() {
      if (
        this.gvStoreYamlDeployVo.yamlDeployHpaInfo.maxReplicas <=
        this.gvStoreYamlDeployVo.yamlDeployHpaInfo.minReplicas
      ) {
        this.$message.error("伸缩范围最小值应小于最大值");
        return false;
      }
      return true;
    },
    getOneServiceDeployInfo(appName, appVersion) {
      this.$appStoreApi
        .getDeployConfig({ appName: appName, appVersion: appVersion })
        .then((res) => {
          if (res && res.code === 200) {
            this.gvStoreYamlDeployVo = res.data;
            this.gvEnvLength = res.data.yamlDeployEnvInfo.length;
            if (this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics === null) {
              this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics = [];
            }
          }
        });
    },
    changePortWithContainer(index) {
      console.log(this.gvStoreYamlDeployVo.yamlDeployPortInfo[index].fixed);
      console.log(this.gvStoreYamlDeployVo);
    },
    deleteEnvForEnvList(index) {
      this.gvStoreYamlDeployVo.yamlDeployEnvInfo.splice(index, 1);
    },
    judgeReg(index) {
      const keyPattern = /^[a-zA-Z][a-zA-Z0-9_]{1,64}$/;
      const labelPattern = /^[a-zA-Z0-9-_./%:; @]{1,64}$/;
      if (
        !keyPattern.test(
          this.gvStoreYamlDeployVo.yamlDeployEnvInfo[index].key
        ) ||
        this.gvStoreYamlDeployVo.yamlDeployEnvInfo[index].key === ""
      ) {
        this.$message.error(
          "环境变量KEY值只能包含字母、数字、_，以字母开头且长度不超过64位"
        );
        return false;
      }
      if (
        !labelPattern.test(
          this.gvStoreYamlDeployVo.yamlDeployEnvInfo[index].value
        ) ||
        this.gvStoreYamlDeployVo.yamlDeployEnvInfo[index].value === ""
      ) {
        this.$message.error(
          "环境变量VALUE值只能包含字母、数字、.、_、-、/等，且长度不超过64位"
        );
        return false;
      }
      this.gvStoreYamlDeployVo.yamlDeployEnvInfo[index].value =
        this.gvStoreYamlDeployVo.yamlDeployEnvInfo[index].value.trim();
      return true;
    },
    addNewEnv() {
      let filter = this.gvStoreYamlDeployVo.yamlDeployEnvInfo.filter(
        (ele) => ele.value === "" || ele.key === ""
      );
      if (filter.length > 0) {
        this.$message.warning("请先将空数据填写完整");
      } else {
        this.gvStoreYamlDeployVo.yamlDeployEnvInfo.push({
          key: "",
          value: "",
        });
      }
    },
    checkCpu() {
      if (
        this.gvStoreYamlDeployVo.yamlDeployResourceInfo.cpuRequest >
        this.remainResourceInfo.cpu
      ) {
        this.$message.error("CPU资源值不能超过可用资源");
        return;
      }
      if (this.gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit) {
        if (
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.cpuLimit >
          this.remainResourceInfo.cpu
        ) {
          this.$message.error("CPU资源值不能超过可用资源");
        }
      }
    },
    checkMemory() {
      if (
        this.gvStoreYamlDeployVo.yamlDeployResourceInfo.memRequest >
        this.remainResourceInfo.memory
      ) {
        this.$message.error("内存资源值不能超过可用资源");
        return;
      }
      if (this.gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit) {
        if (
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.memLimit >
          this.remainResourceInfo.memory
        ) {
          this.$message.error("CPU资源值不能超过可用资源");
        }
      }
    },
    async deployThePackage() {
      if (this.gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit) {
        if (
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.cpuLimit <
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.cpuRequest ||
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.memLimit <
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.memRequest
        ) {
          this.$message.error("开启资源限制时，预留值不能高于限制值");
          return;
        }
      }
      if (
        this.gvStoreYamlDeployVo.yamlDeployResourceInfo.cpuRequest >
        this.remainResourceInfo.cpu
      ) {
        this.$message.error("CPU资源值不能超过可用资源");
        return;
      }
      if (this.gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit) {
        if (
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.cpuLimit >
          this.remainResourceInfo.cpu
        ) {
          this.$message.error("CPU资源值不能超过可用资源");
          return;
        }
      }
      if (this.gvStoreYamlDeployVo.enableHpa) {
        if (this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics.length === 0) {
          this.$message.error("自动伸缩开启后，必须添加触发条件");
          return;
        }
        if (!this.checkReplicas()) {
          return;
        }
      }
      if (
        this.gvStoreYamlDeployVo.yamlDeployResourceInfo.memRequest >
        this.remainResourceInfo.memory
      ) {
        this.$message.error("内存资源值不能超过可用资源");
        return;
      }
      if (this.gvStoreYamlDeployVo.yamlDeployResourceInfo.enableLimit) {
        if (
          this.gvStoreYamlDeployVo.yamlDeployResourceInfo.memLimit >
          this.remainResourceInfo.memory
        ) {
          this.$message.error("内存资源值不能超过可用资源");
          return;
        }
      }
      //设置租户ID
      this.gvStoreYamlDeployVo.tenantId = getTenantId();
      for (
        let i = 0;
        i < this.gvStoreYamlDeployVo.yamlDeployEnvInfo.length;
        i++
      ) {
        let b = this.judgeReg(i);
        if (!b) {
          return;
        }
      }

      //部署名称按照K8s命名规则进行验证
      const regex = /^[a-z0-9]([-a-z0-9]{0,62}[a-z0-9])?$/; // 小写字母或数字开头，后面可以跟连字符，但不能以连字符开头或结尾
      const deployName = this.gvStoreYamlDeployVo.yamlDeployBaseInfo.deployName;

      if (!regex.test(deployName)) {
        // 如果不符合正则表达式的条件，弹出错误信息
        this.$message.error(
          "部署名称必须为1-63位数字或小写字母组成，可以包含连字符，但不能以连字符开头或结尾，并且以字母或数字开头"
        );
        return;
      } else if (deployName === "") {
        this.$message.error("部署名称不能为空，请修改...");
        return;
      }
      let flag = false;
      await this.$appManageApi
        .checkDeployName(this.gvStoreYamlDeployVo.yamlDeployBaseInfo.deployName)
        .then((res) => {
          if (res && res.code === 200) {
            if (res.data) {
              this.$message.error("部署名称已存在，请修改...");
              flag = true;
            }
          }
        });
      if (flag) {
        return;
      }
      for (
        let i = 0;
        i < this.gvStoreYamlDeployVo.yamlDeployPortInfo.length;
        i++
      ) {
        const portInfo = this.gvStoreYamlDeployVo.yamlDeployPortInfo[i];
        if (portInfo.enableDns) {
          if (portInfo.dns === "") {
            this.$message.error(
              `开启域名后，端口 ${portInfo.port} 的域名不能为空，请修改...`
            );
            return;
          }
          let flag1 = false;
          await this.$appManageApi.checkDns(portInfo.dns).then((res) => {
            if (res && res.code === 200) {
              if (res.data) {
                this.$message.error(
                  `端口 ${portInfo.port} 域名已存在，请修改...`
                );
                flag1 = true;
              }
            }
          });
          if (flag1) {
            return;
          }
        }
      }
      //服务实例部署
      this.$appManageApi.deployYaml(this.gvStoreYamlDeployVo).then((res) => {
        if (res && res.code === 200) {
          this.$message.success(res.msg);
          // this.$router.push({
          //   name: "ServiceList",
          // })
          this.startAfterDeploy(res.data);
        }
      });
    },
    startAfterDeploy(deployId) {
      this.$appManageApi.startYamlDeploy([deployId]).then((res) => {
        this.$router.push({
          name: "ServiceList",
        });
        if (res && res.code === 200) {
          this.$message.success(res.msg);
        }
      });
    },
    cancelDeploy() {
      this.$router.push({
        name: "ServicePackage",
      });
    },
    changeResourceLimitStatus(status) {
      if (status) {
        this.resourceLimitText = "开启资源限制";
      } else {
        this.resourceLimitText = "关闭资源限制";
      }
    },
    checkDeployName() {
      const regex = /^[a-z][a-z0-9]{5,63}$/; // 字母开头，后面跟着5位数字或字母
      // const regex = /^[a-zA-Z][a-zA-Z0-9]{5,}$/; // 字母开头，后面跟着5位数字或字母
      const deployName = this.gvStoreYamlDeployVo.yamlDeployBaseInfo.deployName;
      if (!regex.test(deployName)) {
        // 如果不符合正则表达式的条件，弹出错误信息
        this.$message.error(
          "部署名称必须为6-64位数字或字母组成，并且以字母开头"
        );
        return;
      } else if (deployName === "") {
        this.$message.error("部署名称不能为空，请修改...");
        return;
      }
      this.$appManageApi
        .checkDeployName(this.gvStoreYamlDeployVo.yamlDeployBaseInfo.deployName)
        .then((res) => {
          if (res && res.code === 200) {
            if (res.data) {
              this.$message.error("部署名称已存在，请修改...");
            }
          }
        });
    },
    checkDnsValue(dns) {
      // const regex = /^[a-z][a-z0-9]{5,63}$/; // 字母开头，后面跟着5位数字或字母
      // // const regex = /^[a-zA-Z][a-zA-Z0-9]{5,}$/; // 字母开头，后面跟着5位数字或字母
      // if (!regex.test(dns)) {
      //   // 如果不符合正则表达式的条件，弹出错误信息
      //   this.$message.error(
      //     "域名必须为6-64位数字或字母组成，并且以字母开头"
      //   );
      //   return;
      // } else
      if (dns === "") {
        this.$message.error("域名不能为空，请修改...");
        return;
      }
      this.$appManageApi.checkDns(dns).then((res) => {
        if (res && res.code === 200) {
          if (res.data) {
            this.$message.error("域名已存在，请修改...");
          }
        }
      });
    },
    getExistPvcList() {
      this.$storagePvcApi.listAllPvc().then((res) => {
        if (res && res.code === 200) {
          this.existPvcList = res.data;
        }
      });
    },
    getFileDataById(id, mountFilePath, mountFiledata) {
      this.editConfigFileDialog = true;
      this.mountPath = mountFilePath;
      if (mountFiledata === "") {
        this.$appStoreApi
          .getFileData({ id: id, mountFilepath: mountFilePath })
          .then((res) => {
            if (res && res.code === 200) {
              this.configFileContext = res.data;
              this.mountPath = mountFilePath;
            }
          });
      } else {
        this.configFileContext = mountFiledata;
      }
    },
    closeEditConfigFileDialog() {
      this.editConfigFileDialog = false;
    },
    saveConfigFileContext() {
      this.gvStoreYamlDeployVo.yamlDeployConfigInfo.forEach((ele) => {
        if (ele.mountPath === this.mountPath) {
          ele.mountFiledata = this.configFileContext;
        }
      });
      this.editConfigFileDialog = false;
      console.log(this.gvStoreYamlDeployVo.yamlDeployConfigInfo);
    },
    addHapInfoMetrics() {
      if (this.metricsInfo.type === "" || this.metricsInfo.usage === 0) {
        this.$message.warning("请先选择数据，并确保使用量不为0");
        return;
      }
      const existingIndex =
        this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics.findIndex(
          (item) => item.type === this.metricsInfo.type
        );
      if (existingIndex !== -1) {
        // 如果已存在相同的 key，则更新对应的 value
        this.$set(
          this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics,
          existingIndex,
          {
            ...this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics[
            existingIndex
            ],
            ...this.metricsInfo,
          }
        );
      } else {
        // 如果不存在相同的 key，则添加新的数据
        this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics.push({
          ...this.metricsInfo,
        });
      }
      this.metricsInfo = {
        type: "",
        usage: 0,
      };
    },
    deleteMetrics(index) {
      this.gvStoreYamlDeployVo.yamlDeployHpaInfo.metrics.splice(index, 1);
    },
    getMaxResourceInfo() {
      this.$tenantManageApi.getMaxResources().then((res) => {
        if (res && res.code === 200) {
          this.remainResourceInfo = res.data;
        }
      });
    },
  },
  beforeMount() {
    if (this.$route.params.appName === undefined) {
      this.$router.push({
        name: "ServicePackage",
      });
    } else {
      this.getOneServiceDeployInfo(
        this.$route.params.appName,
        this.$route.params.appVersion
      );
      this.getExistPvcList();
      this.getMaxResourceInfo();
    }
  },
};
</script>

<style lang="css">
.el-collapse-item__header {
  font-size: 18px !important;
}

/*.el-switch__label * {*/
/*  font-size: 18px !important;*/
/*}*/
</style>
